<template lang="pug">
.app-container(style="height: 100%;" direction="vertical")
  .filter-container
    el-input.filter-item(v-model='listQuery.title' :placeholder="$t('casesTable.title')" style='width: 600px;' @keyup.enter.native='handleFilter')
    el-button.filter-item(style='margin-left: 1px;' v-waves='' type='primary' icon='el-icon-search' @click='handleFilter')
      | {{ $t('casesTable.search') }}
    el-button.filter-item(style='margin-left: 10px;' type='primary' icon='el-icon-plus' @click='handleCreate')
      | {{ $t('casesTable.addCase') }}
  cases-list(ref="List")
  add-cases-dlg(
    :dialogStatus="dialogStatus"
    :isShowDlg="isShowDlg"
    @on-result-change='onResultChange'
    @on-add-case='onAddCase'
    )
</template>

<script>
import CasesList from './components/CasesList'
import AddCasesDlg from './components/AddCasesDlg'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/filters'

import Pagination from '@/components/Pagination'
import ElDragSelect from '@/components/DragSelect' // base on element-ui
const moment = require('moment')

const caseTypeOptions = [
  { key: 'EC', display_name: '电子商务' },
  { key: 'SA', display_name: '规范促销' },
  { key: 'ES', display_name: '网络交易' },
  { key: 'FS', display_name: '食品安全' }
]

const caseTypeKeyValue = caseTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'CaseList',
  components: { CasesList, AddCasesDlg, Pagination, ElDragSelect },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return caseTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 10,
        title: undefined,
        type: undefined,
        creator: '123456',
        sortField: 'createTime',
        sortRule: -1
      },
      importanceOptions: [1, 2, 3],
      caseTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      inquisitorValue: ['李寻欢', '叶开', '叮当', '傅红雪'],
      inquisitors: [
        { value: '李寻欢', label: '李寻欢' },
        { value: '叶开', label: '叶开' },
        { value: '叮当', label: '叮当' },
        { value: '傅红雪', label: '傅红雪' }
      ],
      temp: {
        description: '',
        createTime: moment().format('YYYY-MM-DD HH:MM:SS'),
        caseName: '',
        caseNo: moment().format('YYYYMMDDHHMMSS'),
        caseType: 'EC',
        status: 'published'
      },

      isShowDlg: false,
      dialogStatus: 'create',

      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  methods: {
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'createTime') {
        this.sortByCreateTime(order)
      }
    },
    sortByCreateTime(order) {
      this.listQuery.sortField = 'createTime'
      if (order === 'ascending') {
        this.listQuery.sortRule = 1
      } else {
        this.listQuery.sortRule = -1
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        description: '',
        createTime: moment().format('YYYY-MM-DD HH:MM:SS'),
        caseName: '',
        caseNo: moment().format('YYYYMMDDHHMMSS'),
        type: '电子商务',
        status: 'published'
      }
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.isShowDlg = true
    },
    onResultChange(val) {
      this.isShowDlg = val
    },
    onAddCase(val) {
      this.isShowDlg = false
      if (val === 'canceld') {
        console.log('')
      } else {
        this.$refs.List.handleFilter()
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.createTime = new Date(this.temp.createTime)
      this.dialogStatus = 'update'
      this.isShowDlg = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateCase() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.createTime = +new Date(tempData.createTime) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          // updateArticle(tempData).then(() => {
          //   const index = this.list.findIndex(v => v.id === this.temp.id)
          //   this.list.splice(index, 1, this.temp)
          //   this.dialogFormVisible = false
          //   this.$notify({
          //     title: '成功',
          //     message: '更新成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      // fetchPv(pv).then(response => {
      //   this.pvData = response.data.pvData
      //   this.dialogPvVisible = true
      // })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['createTime', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'createTime',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped></style>
